/**
 *
 *
 * +----------------------------------------------------------------------------------------------+
 * |Date               |  Version  |Author             |Description                              |
 * |==========+=======+==============+===================|
 * |2018年9月13日     |  1.0.0       | kreo                 |Initial                                       |
 * +----------------------------------------------------------------------------------------------+
 */
package main.java.utils.hxy.thread.thread.sql;

import com.jfinal.log.Logger;
import com.wanma.framework.util.thread.ISinglePoolFactory;

import java.util.List;

/**
 * 执行SQL的线程池, 特点是根据Key去取得线程池,而每个Key的线程池是个单线程池 , 保证每个Key的线程池的SQL的先后执行顺序
 * 
 * @ClassName SQLExecutePoolService
 * @Description
 * 
 */
public class ISQLPool {
	private final static Logger log = Logger.getLogger(ISQLPool.class);
	private final static String DEFAULT_KEY = "SQL_DEFAULT";
	private final static String DEFAULT_BATCH_KEY = "BATCH_SQL_DEFAULT";

	public static ISQLObject addSQL(String key, ISQLObject sqlObject) {
		// Future<ISQLObject> future =
		try {
			ISinglePoolFactory.addCallable(key, new ISQLTask(sqlObject));
			log.debug("AddSQL:" + "[" + key + "]" + "[" + sqlObject.getDbName() + "]" + " : " + sqlObject.getSql());
			// return future.get();
		} catch (Exception e) {
			log.error("AddSQL Error:", e);
		}
		return sqlObject;
	}

	public static ISQLObject addSQL(ISQLObject sqlObject) {
		return addSQL(DEFAULT_KEY, sqlObject);
	}

	public static ISQLObject addSQL(String key, String dbName, String sql, Object[] para) {
		ISQLObject sqlObject = new ISQLObject();
		sqlObject.setDbName(dbName);
		sqlObject.setSql(sql);
		sqlObject.setPara(para);
		return addSQL(key, sqlObject);
	}

	public static ISQLObject addSQL(String key, String dbName, String sql) {
		return addSQL(key, dbName, sql, null);
	}

	public static ISQLObject addSQL(String dbName, String sql) {
		return addSQL(DEFAULT_KEY, dbName, sql, null);
	}

	public static ISQLObject addSQL(String dbName, String sql, Object[] para) {
		return addSQL(DEFAULT_KEY, dbName, sql, para);
	}

	public static List<ISQLObject> addBatchSQL(List<ISQLObject> sqlObjects) {
		return addBatchSQL(DEFAULT_BATCH_KEY, sqlObjects);
	}

	public static List<ISQLObject> addBatchSQL(String key, List<ISQLObject> sqlObjects) {
		// Future<List<ISQLObject>> future =
		try {
			//log.info("线程开始." + System.currentTimeMillis());
			ISinglePoolFactory.addCallable(key, new ISQLBatchTask(sqlObjects));
			log.debug("AddBatchSQL:" + "[" + key + "]" + "SIZE" + ":[" + sqlObjects.size() + "]");
			// return future.get();
		} catch (Exception e) {
			log.error("AddBatchSQL Error:", e);
		}
		return sqlObjects;
	}
}
